/*
 * @Author: your name
 * @Date: 2020-05-22 14:30:04
 * @LastEditTime: 2020-10-30 10:27:52
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /yigo/src/Utils/Util.js
 */ 

import ImagePicker from 'react-native-image-picker';
import codePush from 'react-native-code-push'
import {Platform, Alert} from 'react-native'

export const Business_OrderStatus = [
    {id:0,status:0, name:'已下单',next:'等待用户支付'},
    {id:1,status:1, name:'已支付',next:'等待商家接单'},
    {id:2,status:2, name:'已接单',next:'等待匹配骑手'},
    {id:2,status:3, name:'已匹配',next:'等待骑手取货'},
    {id:3,status:4, name:'已领取',next:'骑手开始送货'},
    {id:4,status:5, name:'已完成',next:'完成全部订单'}
]

export const motor_OrderStatus = [
    {id:1,status:2, name:'我可抢单',next:'等待匹配骑手'},
    {id:2,status:3, name:'我的订单',next:'等待骑手取货'},
    {id:3,status:4, name:'已领取',next:'骑手开始送货'},
    {id:4,status:5, name:'已完成',next:'完成全部订单'}
]

const options = {
    isCamera: true,
    imageCount: 6,
    title: '选择图片',
    cancelButtonTitle: '取消',
    takePhotoButtonTitle: '拍照',
    chooseFromLibraryButtonTitle: '相册',
    cameraType: 'back',
    mediaType: 'photo',
    videoQuality: 'high',
    durationLimit: 10,
    maxWidth: 600,
    maxHeight: 600,
    aspectX: 2,
    aspectY: 1,
    quality: 0.8,
    angle: 0,
    allowsEditing: true,
    noData: false,
    storageOptions: {
      skipBackup: true,
      path: 'images',
      map: new Map()
    }
  }
/**
 * @description: 图片按base64进行上传
 * @param {type} 
 * @return: 
 */
export const Base64 = () => {
    return new Promise((resolve, reject) => {
        //ActionSheet 相机 相册          
        ImagePicker.showImagePicker(options, (response) => {
            console.log("sss:",response);
            if (response.didCancel) {
              console.log('User cancelled image picker');
            }
            else if (response.error) {
              console.log('ImagePicker Error: ', response.error);
            }
            else if (response.customButton) {
              console.log('User tapped custom button: ', response.customButton);
            }
            else {
            let file,name;
            if (Platform.OS === 'android') {
               file = response.uri;
               name = response.fileName
             } else {
               file = response.uri.replace('file://', '');
               const url = response.uri.split('/')
               name = url[url.length - 1]
             }

             const file0 = {uri: file, type: 'multipart/form-data', name};
             const formData = new FormData();
             formData.append('file', file0)
             console.log("图片路径:",file0,formData);
             resolve(formData)
            }
        });  
    })
}

/**
 * 热更新主动检查
 */ 
export const checkUpdate = () => {        
  codePush.checkForUpdate(deploymentKey).then((update) => {
    if (!update) {
        Alert.alert("提示", "已是最新版本--", [
            {
                text: "Ok", onPress: () => {
                console.log("点了OK");
            }
            }
        ]);
    } else {
        codePush.sync({
                deploymentKey: deploymentKey,
                updateDialog: {
                    optionalIgnoreButtonLabel: '稍后',
                    optionalInstallButtonLabel: '立即更新',
                    optionalUpdateMessage: '有新版本了，是否更新？',
                    title: '更新提示'
                },
                installMode: codePush.InstallMode.IMMEDIATE,
 
            },
            (status) => {
                switch(status) {
                    case codePush.SyncStatus.CHECKING_FOR_UPDATE:
                        console.log("Checking for updates.");
                    break;
                        case codePush.SyncStatus.DOWNLOADING_PACKAGE:
                        console.log("Downloading package.");
                    break;
                        case codePush.SyncStatus.INSTALLING_UPDATE:
                        console.log("Installing update.");
                    break;
                        case codePush.SyncStatus.UP_TO_DATE:
                        console.log("Installing update.");
                    break;
                        case codePush.SyncStatus.UPDATE_INSTALLED:
                        console.log("Update installed.");
                    break;
        }
            },
            (progress) => {
                console.log(progress.receivedBytes + " of " + progress.totalBytes + " received.");
            }
        );
    }
 }).catch((error) => {
     console.log("热更新回调失败:",error);
 })
}


/**
 * 
 * @param {时间戳转日期} shijianchuo 
 */
export const getTime = (shijianchuo) => {
    function add0(m) {
            return m < 10 ? '0' + m : m
    }    
    if (!shijianchuo) return '-'
        var time = new Date(parseFloat(shijianchuo));
    
        var y = time.getFullYear();
    
        var m = time.getMonth() + 1;
    
        var d = time.getDate();
    
        var h = time.getHours();
    
        var mm = time.getMinutes();
    
        var s = time.getSeconds();
    
    //     return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm)
        return y + '-' + add0(m) + '-' + add0(d)
}
/**
 * 
 * @param {日期转字符串} dateStr 
 */
export const getUnixTime = (dateStr) => {
    var newstr = dateStr.replace(/-/g,'/'); 
    var date =  new Date(newstr); 
    var time_str = date.getTime().toString();
    return time_str.substr(0, 10);
}
 
// getUnixTime('2019-06-17 23:11:54');
// console.log(getUnixTime('2019-06-17 23:11:54'));//156078431
/**
 * 
 * @param {字符串是否是汉字} str 
 */
export const isChn = (str) => {
    if (typeof str === 'string' || typeof str === 'number') {
        if (escape(str).indexOf( "%u" )<0){            
            return false;
        } else {
            console.log( "包含中文:",str );
            return true;
        }
    } else {
        console.log("需要转码的字符串不正常:",str, typeof str);
    }
    return true;
}
/**
 * 
 * @param {*} 原数组 
 * @param {*} 获取数组的特定值 
 * @param {*} 获取数组的特定值
 */
export const unitArray = (array,value, label,Linkman="") => {
    let tempArr = [];
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        let temp = {value: element[label], label: element[value]};
        if (Linkman !== "") {
            temp.Contacts = element[Linkman];
        }
        tempArr.push(temp)
    }    
    return tempArr
}

/**
 * 
 * @param {*} 原字符串 
 * @param {*} 开始位置 
 * @param {*} 结束位置 
 * @param {*} 替换为**** 
 */
export const replacepos = (text,start,stop,replacetext) => {
    return text.substring(0, start) + replacetext + text.substring(stop);
}

/**
 * 
 * @param {*} 身份证合法性验证
 */
export function IdentityCodeValid(code) {
    var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
    var tip = "";
    var pass= true;
  
    if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
      tip = "身份证号格式错误";
      pass = false;
    }
  
    else if(!city[code.substr(0,2)]){
      tip = "地址编码错误";
      pass = false;
    }
    else{
      //18位身份证需要验证最后一位校验位
      if(code.length == 18){
        code = code.split('');
        //∑(ai×Wi)(mod 11)
        //加权因子
        var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
        //校验位
        var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
        var sum = 0;
        var ai = 0;
        var wi = 0;
        for (var i = 0; i < 17; i++)
        {
          ai = code[i];
          wi = factor[i];
          sum += ai * wi;
        }
        var last = parity[sum % 11];
        if(parity[sum % 11] != code[17]){
          tip = "校验位错误";
          pass =false;
        }
      }
    }
    //if(!pass) alert(tip);
    return pass;
  }


/**
 * 
 * @param {*} 统一社会信用代码合法性校验 
 */
export  function CheckSocialCreditCode(Code) { 
//   　　var patrn = /^[0-9A-Z]+$/;
       var patrn = /^[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}$/g
   　　//18位校验及大写校验
  　　 if ((Code.length != 18) || (patrn.test(Code) == false)) 
  　　　　{ 
  　　　　　　alert("不是有效的统一社会信用编码！---");
           return false;
  　　　　 } 
  　　else 
  　　{ 
  　　　　var Ancode;//统一社会信用代码的每一个值
   　　　　var Ancodevalue;//统一社会信用代码每一个值的权重 
  　　　　var total = 0; 
  　　　　var weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];//加权因子 
  　　　　var str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
  　　　　//不用I、O、S、V、Z 
  　　　　for (var i = 0; i < Code.length - 1; i++) 
  　　　　{
   　　　　Ancode = Code.substring(i, i + 1); 
  　　　　Ancodevalue = str.indexOf(Ancode); 
  　　　　total = total + Ancodevalue * weightedfactors[i];
  　　　　//权重与加权因子相乘之和 
  　　　　}
   　　　　var logiccheckcode = 31 - total % 31;
  　　　　if (logiccheckcode == 31)
  　　　　{
  　　　　　　logiccheckcode = 0;
  　　　　}
  　　　　var Str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";
  　　　　var Array_Str = Str.split(',');
  　　　　logiccheckcode = Array_Str[logiccheckcode];
  
  
  　　　　 var checkcode = Code.substring(17, 18);
  　　　　 if (logiccheckcode != checkcode) 
  　　　　{ 
//   　　　　　　alert("不是有效的统一社会信用编码！"); 
           return false;
   　　　　}
   　　}
   return true; 
  　}


